package com.qf.mao.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 啾咪小魔王
 * @date 2022/4/6 10:10
 * @since JDK 1.8
 */
@SuppressWarnings("all")
public class DBUtils {
    private static final Properties PROPERTIES = new Properties();
    private static DataSource dataSource;
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();

    static {
        try {
            PROPERTIES.load(DBUtils.class.getResourceAsStream("/JDBC.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(PROPERTIES);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }
    public static Connection getConn(){
        Connection connection = THREAD_LOCAL.get();
        if (connection == null) {
            //说明是第一次来获取线程的 就从连接池（dataSource）拿出来一个
            try {
                Connection dataSourceConnection = dataSource.getConnection();
                //在存进该线程中去
                THREAD_LOCAL.set(dataSourceConnection);
                return dataSourceConnection;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }
    //提供关闭的方法
    public static void closeAll(AutoCloseable ... autoCloseables){
        for (AutoCloseable autoCloseable:autoCloseables) {
            if(autoCloseable != null){
                try {
                    autoCloseable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
